from flask import Flask, request, Response, session, jsonify, redirect, url_for, render_template, send_from_directory
import flask_config
from gevent import pywsgi
from flask_cors import CORS
import os
from base64 import b64encode
from loguru import logger
from agnes_app import bp_agnes
from angle_app import bp_angle
from mrlic_app import bp_mrlic


logger.add("ssh_remote_connetc.log", level="INFO", rotation="1 week", retention="10 days")
app = Flask(__name__)
app.config.from_object(flask_config)
app.register_blueprint(bp_agnes)
app.register_blueprint(bp_angle)
app.register_blueprint(bp_mrlic)

@app.route("/favicon.ico")
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),'title.ico')

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/login")
def login():
    # verify passwd and username, pass : set session; fail: alter message.
    return render_template("login.html")

@app.route("/verify", methods=["POST"])
def login_verify():
    # verify passwd and username, pass : set session; fail: alter message.
    # session会经过加密再存储到cookie中，所以我们的敏感信息会放在session中, session中不允许存放用户密码，即使不知道密钥也可以破解
    try:
        username = request.form.get("username")
        password = request.form.get("password")
        if username == "admin" and password == "devops123":
            # 设置session status
            session["status"] = "verified"
            logger.debug("verified successful and set session ~")
            return jsonify("pass")
        else:
            return jsonify("failed")
    except Exception as e:
        logger.error(e)

@app.route("/logout")
def logout():
    # 删除session status 字段，返回首页
    if session.get("status"):
        del session["status"]
    return jsonify("delete session successful")


@app.route("/debug")
def debug():
    # get session status,判断admin管理员员是否已登录, true: debug.html; false: reject login.html
    status = session.get("status")
    if status and status == "verified":
        return render_template("debug.html")
    else:
        return render_template("login.html")

@app.route("/return_interface")
def return_interface():
    arrary = [url_for("return_interface"), url_for("agnes.get_status"), url_for("angle.get_status"), url_for("mrlic.query_downloading_build"), url_for("mrlic.query_download_rules"), url_for("mrlic.query_all_builds"), url_for("get_tocken"), url_for("mrlic.query_nas_all_builds"), url_for("mrlic.insert_rule")]
    return jsonify(arrary)

@app.route("/get_tocken")
def get_tocken():
    tocken = b64encode(b'2022-09-08 12:05:12 MR Devops').decode("utf8")
    return jsonify({"tocken": tocken})

@app.errorhandler(404)
def error(err):
    return render_template("error.html")

if __name__ == '__main__':
    # 开启WSGI server, 绑定listener and application
    server = pywsgi.WSGIServer(listener=("0.0.0.0", 8089), application=app)
    CORS(app, supports_credentials=True)
    # app.run(host="0.0.0.0", port=8080)
    server.serve_forever()
